<template>
    <div class="main-contain order-confirm">
      <p class="page-title">订单确认</p>
      <el-descriptions class="" :column="1" border v-if="currDetailData!=null">
        <el-descriptions-item label="商品名称">{{currDetailData.name}}</el-descriptions-item>
        <el-descriptions-item label="商品内容">
            <div class="order-item">
              <el-avatar shape="square" size="medium" :src="currDetailData.mainPic" style="float: left;"></el-avatar>
              <div>
                <div>{{ currDetailData.describ }}</div>
              </div>
              <!-- <el-button size="mini" v-if="item.item.iscomment==0" class="green-button" @click="showCommentDialog(currDetailData.order, item.product)">评论</el-button> -->
            </div>
        </el-descriptions-item>
        <el-descriptions-item label="所需积分">
          <p>
            <span style="color: #d4571d;">
              {{ currDetailData.price }}
            </span>
          </p>
        </el-descriptions-item>
        <el-descriptions-item label="我的积分">
            <span style="font-size: 22px; color: #78a355;">
            {{ currUser.user.points }}
            </span>
        </el-descriptions-item>
      </el-descriptions>
      <el-form
          label-width="120px"
          :model="editForm"
          :rules="rules"
          ref="formRef"
          class="form-div"
        >
          <el-form-item label="姓名" prop="realName">
            <el-input v-model="editForm.realName" auto-complete="off" ></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="editForm.mobile" auto-complete="off" ></el-input>
          </el-form-item>
          <el-form-item label="收货地址" prop="address">
            <el-input v-model="editForm.address" auto-complete="off" placeholder=""></el-input>
          </el-form-item>
        </el-form>
      <div class="show-btn">
        <el-button type="info" icon="Back" @click="goBack()">返回</el-button>
        <el-button type="success" icon="Check" class="button orange-button" @click="submitOrder()"
           v-if="currUser.user.points>currDetailData.price" style="background-color:#78a355;">确认兑换</el-button>
        <el-button type="info" icon="Check" class="button orange-button" v-else>积分不足</el-button>
      </div>
  
      <!--支付对话框-->
      <el-dialog
        title="支付"
        v-model="payVisible"
        width="60%"
        :close-on-click-modal=false
        :show-close="false"
      >
      <el-descriptions class="margin-top" :column="2" border v-if="currDetailData!=null">
        <el-descriptions-item label="订单编号">{{currDetailData.orderCode}}</el-descriptions-item>
        <el-descriptions-item label="订单金额">
          ￥
          <span style="font-size: 22px; color: #d4571d;">
            {{ formatAmount(currDetailData.totalPrice) }}
          </span>
        </el-descriptions-item>
        
      </el-descriptions>
      <div class="pay-btn">
        <div class="qr-code">
          <img src="http://129.211.222.131:18080/images/pay.png" alt="" style="width: 200px;height: 200px;">
        </div>
        <el-button size="mini" icon="Close" type="info" @click="onCancel()">取消</el-button>
        <el-button size="mini" icon="Check" type="primary" @click="onPay()">已支付</el-button>
      </div>
      </el-dialog>
    </div>
  </template>

<script setup lang="ts">
import { ref, reactive, nextTick, computed, toRef } from "vue";
import baseService from "@/service/baseService";
import { ElMessage, ElMessageBox } from "element-plus";
import { timestampToDayHM, timestampToHM, timestampToDate, formatAmount } from "@/utils/utils"
import { fileUploader } from '@/utils/upload.js'
import { useRouter, useRoute } from 'vue-router'
import { EluiChinaAreaDht } from 'elui-china-area-dht'
import { getCache, removeCache } from "@/utils/cache";
import { CacheToken } from "@/constants/cacheKey";
import { useStore } from 'vuex';

// 查询参数
const queryForm = reactive({
    deptName: "",
    pageNo: 1,
    pageSize: 10
});
const router = useRouter();
const route = useRoute();
// 列表内容数量
const total = ref(0);
// 列表是否加载
const loading = ref(true);
// 列表返回值
const list = ref<any[]>([]);

// 表单实例
const formRef = ref();
const addressRef = ref();
// 是否打开弹出框
const open = ref(false);
const payVisible = ref(false);
const addressFormopen = ref(false);
// 弹出框标题
const title = ref("");
const addressList = ref<any[]>([]);
const currDetailData = ref();
const currTotalAmt = ref(0)
const store = useStore();

// 表单验证
const rules = ref({
    deptName: [{ required: true, message: "规则名称不能为空", trigger: "blur" }],
});

// 订单表单数据
let editForm = toRef(
  reactive({
    productId: '',
    realName: '',
    address: '',
    mobile: ''
  })
)

function onCancel(){
    router.back()
}

function goBack(){
  router.back()
}

const currUser = computed(() => store.state.frontUser);

const onInit = () => {
  const userInfo = getCache(CacheToken);
  baseService.get(`/api/opera/load/user/${userInfo.user.userId}`).then((res) => {
    if (res.code === 200) {
      userInfo.user=res.data
      store.commit('setFrontLoginUser', userInfo);
    }
  });
};

const onPay = ()=>{
  let orderCode = editForm.value.productId
  baseService.get(`/api/order/pay/${orderCode}`).then((res) => {
      loading.value = false;
      ElMessage.success("兑换成功");
      router.push("/order/my/list");
  }).catch(() => {
    ElMessage.error("支付异常");
      loading.value = false;
  });
}

function onNewAdd(){
    addressFormopen.value = true
    console.log('NNNNNNNNNNN')
}

//获取预览订单
const getInfo = () => {
    const pid = route.query.pid
    console.log('从路由获取参数：', route.query)
    baseService.get(`/api/product/detail/${pid}`).then((res) => {
        console.log('获取产品详情：',res)
        currDetailData.value = res.data.product;
        loading.value = false;
    }).catch(() => {
        loading.value = false;
    });
}

//提交订单
const submitOrder = ()=>{
  editForm.value.productId = currDetailData.value.productId
  baseService.post(`/api/order/save`, editForm.value).then((res) => {
      loading.value = false;
      if(res.success){
        ElMessage.success('兑换成功');
        router.push("/order/my/list");
      }else{
        ElMessage.error('兑换失败！');
      }
    }).catch(() => {
        loading.value = false;
    });
}

getInfo();
onInit();
</script>

<style scoped>
.page-title {
    font-size: 16px;
    font-weight: bold;
    color: #0038a7;
    padding-left: 5px;
    border-left: 3px solid #0038a7;
    margin: 15px 0;
    height: 30px;
    line-height: 30px;
}
.margin-top{
  width: 80%;
  margin: 15px auto;
}
.form-div{
  width: 80%;
  margin: 20px auto;
}
.show-btn{
  text-align: center;
  margin: 10px 0 30px 0;
}

.main-contain .el-form-item {
    margin-bottom: 20px;
}
.order-confirm{
  width: 860px;
}
.new-add{
  margin-top: 20px;
}
.qr-code, .pay-btn{
  text-align: center;
}
.qr-code{
  margin: 12px 0;
}
.order-item{
  clear: both;
  padding: 6px 0;
  line-height: 20px;
  font-size: 13px;
}
.order-item p{
  margin: 0;
  padding: 0;
}
.order-item .opname{
  padding-left: 4px;
  color: #666;
}
</style>